package com.lingz.manager.modules.wuxue.serviceimpl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lingz.manager.modules.wuxue.dao.DeviceInfoDao;
import com.lingz.manager.modules.wuxue.mapper.DeviceInfoMapper;
import com.lingz.manager.modules.wuxue.mapper.TuopuInsectDataMapper;
import com.lingz.manager.modules.wuxue.entity.DeviceInfo;
import com.lingz.manager.modules.wuxue.entity.vo.DeviceAllInfo;
import com.lingz.manager.modules.wuxue.service.DeviceInfoService;
import com.lingz.manager.modules.wuxue.utils.BeanCopyUtils;
import com.lingz.manager.modules.wuxue.utils.SendRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
@Transactional
public class DeviceInfoServiceImpl implements DeviceInfoService {

    @Autowired
    DeviceInfoDao deviceInfoDao;

    @Autowired
    DeviceInfoMapper deviceInfoMapper;

    @Autowired
    TuopuInsectDataMapper tuopuInsectDataMapper;

    @Override
    public DeviceInfoDao getRepository(){return deviceInfoDao;}

    public void requestDeviceInfoToDB() {

        String HSdeviceInfo = "https://www.cebaowang.com:8089/external/data/upload?deviceId=YBQ0000145&startDate=2023-10-01%2000:00:00&endDate=2023-12-01%2000:00:00&token=5d95fba9a30e4bb9a6b888d847772200";
        String SXdeviceInfo = "https://telemo.org/pest/data/grid/lureDataview.do?username=tplndj&password=123456";
        String YKMdeviceInfo = "https://telemo.org/pest/data/grid/lureDataview.do?username=wxszbz&password=123456";

        SendRequest request = new SendRequest();

        handleDeviceInfo(HSdeviceInfo,request);
        handleDeviceInfo(SXdeviceInfo,request);
        handleDeviceInfo(YKMdeviceInfo,request);

    }

    @Override
    public List<DeviceInfo> findListDeviceInfo(DeviceInfo deviceInfo) {
        LambdaQueryWrapper<DeviceInfo> wrapper = Wrappers.lambdaQuery(DeviceInfo.class);
        List<DeviceInfo> list = deviceInfoMapper.selectList(wrapper);
        return list;
    }

    @Override
    public DeviceInfo findDeviceInfoById(String id) {
        return deviceInfoMapper.selectById(id);
    }

    @Override
    public List deviceQuantityStatistics() {
        QueryWrapper<DeviceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("device_type, COUNT(*) as count")
                .groupBy("device_type");
        return deviceInfoMapper.selectMaps(queryWrapper);
    }

    @Override
    public List deviceStatus() {
        // 正常0 异常1 离线2
        QueryWrapper<DeviceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("device_type", "SUM(CASE WHEN state = 0 THEN 1 ELSE 0 END) AS normalCount",
                        "SUM(CASE WHEN state = 1 THEN 1 ELSE 0 END) AS abnormalCount",
                        "SUM(CASE WHEN state = 2 THEN 1 ELSE 0 END) AS offlineCount")
                .groupBy("device_type");
        return deviceInfoMapper.selectMaps(queryWrapper);
    }

    @Override
    public List<DeviceInfo> findDeviceInfoByType(String deviceType) {
        LambdaQueryWrapper<DeviceInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceInfo::getDeviceType, deviceType);
        wrapper.orderByAsc(DeviceInfo::getState);
        return deviceInfoMapper.selectList(wrapper);
    }

    @Override
    public String addDeviceInfo(DeviceInfo deviceInfo) {
         deviceInfoMapper.insert(deviceInfo);
         return "添加成功";
    }

    @Override
    public String editDeviceInfo(DeviceInfo deviceInfo) {
        deviceInfoMapper.updateById(deviceInfo);
        return "修改成功";
    }

    @Override
    public String deleteDeviceInfo(String[] ids) {
        deviceInfoMapper.deleteBatchIds(Arrays.asList(ids));
        return "删除成功";
    }

    @Override
    public List<DeviceInfo> findDeviceInfoByPosition(String position) {
        LambdaQueryWrapper<DeviceInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceInfo::getPosition, position);
        wrapper.orderByAsc(DeviceInfo::getState);
        return deviceInfoMapper.selectList(wrapper);
    }

    @Override
    public ArrayList<ArrayList<DeviceInfo>> findDeviceInfoGroupByPosition() {
        List<DeviceInfo> deviceInfoList = findListDeviceInfo(null);
        ArrayList<ArrayList<DeviceInfo>> lists = new ArrayList<>();
        ArrayList<DeviceInfo> list = new ArrayList<>();
        deviceInfoList.stream().sorted(Comparator.comparing(DeviceInfo::getPosition)).forEach(deviceInfo -> {
            if(list.isEmpty() || list.get(0).getPosition().equals(deviceInfo.getPosition())) {
                list.add(deviceInfo);
            }else {
                lists.add(new ArrayList<>(list));
                list.clear();
                list.add(deviceInfo);
            }
        });
        if(!list.isEmpty()) {
            lists.add(list);
        }
        return lists;
    }

    @Override
    public List<DeviceAllInfo> findDeviceAllInfo() {
        LambdaQueryWrapper<DeviceInfo> wrapper = Wrappers.lambdaQuery(DeviceInfo.class);
        List<DeviceInfo> list = deviceInfoMapper.selectList(wrapper);
        List<DeviceAllInfo> deviceAllInfos = BeanCopyUtils.copyBeanList(list, DeviceAllInfo.class);
        deviceAllInfos.forEach(deviceAllInfo -> {
            String deviceId = deviceAllInfo.getDeviceId();
            if(deviceId != null && deviceId.equals("6B2A9319F8E0")) {
                String url = tuopuInsectDataMapper.getLatestImgUrlByDeviceId(deviceId);
                deviceAllInfo.setLatestImgUrl(url);
            }
        });
        return deviceAllInfos;
    }


    private void handleDeviceInfo(String deviceUrl, SendRequest request){
        String jsonResponse = request.sendGet(deviceUrl);
        JSONObject responseJson = JSONObject.parseObject(jsonResponse);

        List<String> processedIds = new ArrayList<>();
        List<DeviceInfo> list = new ArrayList<>();

        if(responseJson != null){
            JSONArray data = responseJson.getJSONArray("data");
            JSONArray resultData = responseJson.getJSONArray("resultData");
            if(data!= null && !data.isEmpty()){
                for(int i = 0 ; i <data.size(); i++){
                    JSONObject dataObject = data.getJSONObject(i);
                    JSONObject device = dataObject.getJSONObject("device");
                    String deviceId = device.getString("id");

                    DeviceInfo p = new DeviceInfo();
                    DeviceInfo deviceInfo = deviceInfoMapper.selectById(device.getString("id"));

                    if(deviceInfo == null && !processedIds.contains(deviceId)){
                        p.setDeviceId(device.getString("id"));
//                        p.setAddress(device.getString("address"));
//                        p.setBranch(device.getString("branch"));
                        p.setCreatedBy(device.getString("createdBy"));
                        p.setCreatedOn(device.getString("createdOn"));
//                        p.setDirector(device.getString("director"));
                        p.setLatitude(device.getString("lat"));
                        p.setLongitude(device.getString("lng"));
                        p.setModifiedOn(device.getString("modifiedOn"));
                        p.setPhone(device.getString("phone"));
//                        p.setState(device.getString("state"));
                        p.setUpdatedBy(device.getString("updatedBy"));

                        list.add(p);
                        processedIds.add(p.getDeviceId());
                    }
                }
            }else if(resultData != null && !resultData.isEmpty()){
                for(int i = 0 ; i <resultData.size(); i++){
                    JSONObject resultObject = resultData.getJSONObject(i);
                    String deviceId = resultObject.getString("deviceId");
                    DeviceInfo p = new DeviceInfo();
                    DeviceInfo deviceInfo = deviceInfoMapper.selectById(resultObject.getString("id"));
                    if(deviceInfo == null && !processedIds.contains(deviceId)){
                        p.setDeviceId(resultObject.getString("deviceId"));
                        p.setModelNum(resultObject.getString("modelNum"));
                        p.setStartDate(resultObject.getString("startDate"));
                        p.setEndDate(resultObject.getString("endDate"));
//                        p.setDueValidity(resultObject.getString("dueValidity"));
//                        p.setCnName(resultObject.getString("cnName"));
//                        p.setLureName(resultObject.getString("lureName"));

                        list.add(p);
                        processedIds.add(p.getDeviceId());
                    }

                }
            }
            deviceInfoMapper.insertBatch(list);
        }
    }
}

